<template>
  <!-- 加载gltf模型 -->
  <div id="scene"></div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";

let scene; //场景
let camera; //相机
let renderer; //创建渲染器
let controls; //控制器
export default {
  name: "Scene",
  data() {
    return {
      height: {
        value: 0,
      },
    };
  },
  mounted() {
    this.init();
    this.createControls();
    this.addGLTF();
    this.render();
  },
  methods: {
    init() {
      //创建场景
      scene = new THREE.Scene();

      const container = document.getElementById("scene");
      const width = container.clientWidth;
      const height = container.clientHeight;
      /**
       * 透视投影相机设置
       */
      camera = new THREE.PerspectiveCamera(60, width / height, 1, 100000);
      camera.position.set(600, 900, 600); // 树上面观察
      camera.lookAt(scene.position); // 设置相机方向(指向的场景对象)
      // 创建渲染器对象
      renderer = new THREE.WebGLRenderer({ alpha: true });
      renderer.setSize(width, height); // 设置渲染区域尺寸
      container.appendChild(renderer.domElement); // body元素中插入canvas对象
      //创建点光源和环境光源
      const point = new THREE.PointLight(0xffffff);
      point.position.set(600, 900, 600); // 点光源位置
      scene.add(point); // 点光源添加到场景中
      // 环境光
      const ambient = new THREE.AmbientLight(0x888888);
      scene.add(ambient);
    },
    createControls() {
      controls = new OrbitControls(camera, renderer.domElement);
    },
    render() {
      renderer.render(scene, camera);
      requestAnimationFrame(this.render); // 请求再次执行渲染函数render
    },
    addGLTF() {
      const loader = new GLTFLoader();
      loader.load("/model/shanghai.gltf", (gltf) => {
        scene.add(gltf.scene);
      });
    },
  },
};
</script>

<style scoped lang="less">
#scene {
  width: 100%;
  height: 100%;
}
</style>
